import React, {useEffect, useRef} from 'react';
import { forwardRef } from 'react';
import './index.scss';
import * as echarts from "echarts";

export interface FireDeviceData {
  name: string;     // 设备名称，如"喷淋"、"烟感/温感"
  value: number;    // 设备数量
  color: string;    // 设备颜色
}

export interface FirePieChartProps {
  // 容器样式
  width?: number;
  height?: number;
  backgroundColor?: string;
  borderRadius?: number;

  // 数据
  data?: FireDeviceData[];
  totalValue?: number; // 总数值，用于计算百分比

  // 饼图样式
  pieSize?: number;
  pieStrokeWidth?: number;
  pieStrokeColor?: string;

  // 中心数值样式
  showCenterValue?: boolean;
  centerValue?: number | string;
  centerValueFontSize?: number;
  centerValueColor?: string;
  centerValueFontFamily?: string;
  centerValueFontWeight?: number;
  centerValueTextShadow?: string;
  centerValueBackground?: string;

  // 中心标签样式
  showCenterLabel?: boolean;
  centerLabel?: string;
  centerLabelFontSize?: number;
  centerLabelColor?: string;
  centerLabelFontFamily?: string;
  centerLabelFontWeight?: number;

  // 图例样式
  showLegend?: boolean;
  legendPosition?: 'right' | 'bottom';
  legendFontSize?: number;
  legendColor?: string;
  legendFontFamily?: string;
  legendFontWeight?: number;
  legendGap?: number;
  legendItemGap?: number;

  // 事件
  onSliceClick?: (data: FireDeviceData, index: number) => void;

  // 其他属性
  style?: React.CSSProperties;
  className?: string;
  __designMode?: string;
  componentId?: string;
  _componentName?: string;
  forwardRef?: any;
}

const FirePieChart = forwardRef<HTMLDivElement, FirePieChartProps>((props, ref) => {
  const {
    // 容器样式
    width = 400,
    height = 200,
    backgroundColor = 'transparent',
    borderRadius = 0,

    // 数据
    data = [
      { name: '喷淋', value: 320, color: '#93DBFF' },
      { name: '烟感/温感', value: 280, color: '#5AF3B8' },
      { name: '应急灯', value: 180, color: '#FF6F64' },
      { name: '消防栓', value: 150, color: '#FFD982' },
      { name: '喇叭', value: 120, color: '#2297FF' },
      { name: '安全疏散指示灯', value: 156, color: '#4D74FF' }
    ],
    totalValue = 1206,

    // 饼图样式
    pieSize = 137,
    pieStrokeWidth = 0,
    pieStrokeColor = 'transparent',

    // 中心数值样式
    showCenterValue = true,
    centerValue = 1206,
    centerValueFontSize = 24,
    centerValueColor = '#FFFFFF',
    centerValueFontFamily = 'DINAlternate',
    centerValueFontWeight = 700,
    centerValueTextShadow = '0px 0px 7px rgba(0,126,215,0.4)',
    centerValueBackground = 'linear-gradient(90deg, #FFFFFF 0%, #81C6FF 100%)',

    // 中心标签样式
    showCenterLabel = true,
    centerLabel = '消防栓',
    centerLabelFontSize = 12,
    centerLabelColor = '#FFFFFF',
    centerLabelFontFamily = 'SourceHanSansSC',
    centerLabelFontWeight = 500,

    // 图例样式
    showLegend = true,
    legendPosition = 'right',
    legendFontSize = 14,
    legendColor = '#FFFFFF',
    legendFontFamily = 'SourceHanSansSC',
    legendFontWeight = 400,
    legendGap = 20,
    legendItemGap = 16,

    // 事件
    onSliceClick,

    // 其他属性
    style = {},
    className = '',
    __designMode,
    componentId,
    _componentName,
    forwardRef: forwardRefProp,
    ...otherProps
  } = props;

  // 计算饼图路径
  const calculatePieSlice = (startAngle: number, endAngle: number, radius: number) => {
    const x1 = radius * Math.cos(startAngle);
    const y1 = radius * Math.sin(startAngle);
    const x2 = radius * Math.cos(endAngle);
    const y2 = radius * Math.sin(endAngle);

    const largeArcFlag = endAngle - startAngle > Math.PI ? 1 : 0;

    return [
      `M 0 0`,
      `L ${x1} ${y1}`,
      `A ${radius} ${radius} 0 ${largeArcFlag} 1 ${x2} ${y2}`,
      'Z'
    ].join(' ');
  };

  // 计算每个扇形的角度
  const calculateAngles = () => {
    let currentAngle = -Math.PI / 2; // 从12点钟方向开始
    return data.map(item => {
      const sliceAngle = (item.value / totalValue) * 2 * Math.PI;
      const startAngle = currentAngle;
      const endAngle = currentAngle + sliceAngle;
      currentAngle = endAngle;
      return { ...item, startAngle, endAngle, sliceAngle };
    });
  };

  const angles = calculateAngles();
  const radius = (pieSize - pieStrokeWidth) / 2;

  const containerStyle: React.CSSProperties = {
    width: typeof width === 'number' ? `20vw` : width,
    height: typeof height === 'number' ? `18vh` : height,
    minHeight: '194px',
    maxHeight: '230px',
    minWidth: '390px',
    maxWidth: '600px',
    ...style
  };
  const chartRef = useRef<HTMLDivElement>(null);
  const myChartData = [
    { value: 1048, name: '喷淋' },
    { value: 735, name: '烟感/温感' },
    { value: 580, name: '应急灯' },
    { value: 484, name: '消防栓' },
    { value: 300, name: '喇叭' }
  ]
  useEffect(() => {
    if (chartRef.current && myChartData) {
      const chartInstance = echarts.init(chartRef.current);
      const option = {
        legend: {
          top: 'center', // 顶部位置
          right: '1%',
          orient: 'vertical',
          icon: 'roundRect',
          itemHeight: 4,
          itemWidth: 4,
          textStyle: {
            fontSize: 12,
            color: 'rgba(255, 255, 255, 0.8)'
          },
        },
        title: {
          show: true,
          text: myChartData[1].value,
          top: '40%',
          left: '33%',
          textAlign: 'center',
          textVerticalAlign: 'center',
          itemGap: 5,
          textStyle: {
            overflow: 'break',
            fontSize: 18,
            color: 'rgba(255,255,255,0.8)'
          },
          subtext: myChartData[1].name,
          subtextStyle: {
            overflow: 'break',
            fontSize: 10,
            color: 'rgba(255,255,255,0.8)'
          },
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: ['60%', '73%'],
            center: ['35%', '50%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 40,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: myChartData
          },
          {
            name: 'Access From',
            type: 'pie',
            radius: ['43%', '55%'],
            center: ['35%', '50%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 40,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            itemStyle: {
              opacity: 0.5,
            },
            data: myChartData
          }
        ]
      };
      chartInstance.setOption(option);
      window.addEventListener('resize', () => chartInstance.resize());
      return () => {
        chartInstance.dispose();
      };
    }
  }, [myChartData]);

  const firePieChartClassName = ['fire-pie-chart', className].filter(Boolean).join(' ');

  return (
    <div
      ref={ref}
      className={firePieChartClassName}
      style={containerStyle}
      data-component-id={componentId}
      data-component-name={_componentName}
      data-design-mode={__designMode}
      {...otherProps}
    >
      <div className="left-wrap">
        <div style={{backgroundImage: 'url(static/images/xiaofanganquan/fire-fighting-icon.png)', width: '52px', height: '52px', backgroundSize: 'cover'}} />
        <div className="value-wrap">
          <div className="value">
            <div>57791</div>
            <span style={{fontSize: '12px'}}>个</span>
          </div>
          <div className="name">消防设施情况</div>
        </div>
      </div>
      <div className="chart-area">
        <div className="chart-container" ref={chartRef} style={{ width: '100%', height: '100%' }}>
        </div>
      </div>
    </div>
  );
});

FirePieChart.displayName = 'FirePieChart';

export default FirePieChart;
